package com.yjd.comm.base.filter;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.PropertiesCacheUtil;
import com.yjd.comm.vo.Constant;

public class DefaultFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		initFilter(request, response);
		chain.doFilter(request, response);
	}

	private void initFilter(ServletRequest request, ServletResponse response) {
		request.setAttribute("FPWEB", PropertiesCacheUtil
				.get(Constant.PropertiesFileEnum.WEB.getFilename()));
		request.setAttribute("FPWEB_JSON", PropertiesCacheUtil
				.getJson(Constant.PropertiesFileEnum.WEB.getFilename()));
		decodeGet((HttpServletRequest) request, (HttpServletResponse) response);
	}

	/**
	 * 
	 * 处理get乱码
	 * 
	 * @param request
	 * @param response
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void decodeGet(HttpServletRequest request,
			HttpServletResponse response) {
		boolean isGet = "GET".equalsIgnoreCase(request.getMethod());
		Map paramMap = request.getParameterMap();
		for (Iterator<String> iter = paramMap.keySet().iterator(); iter.hasNext();) {
			String key = iter.next();
			Object obj = paramMap.get(key);
			if (obj != null && (obj instanceof String[])) {
				String[] paraValues = (String[]) obj;
				for (int i = 0; i < paraValues.length; i++) {
					String s = isGet ? FrameUtil.decodeStr(paraValues[i]) : paraValues[i];
					if (s != null) {
						s = s.trim();
					}
					paraValues[i] = s;
				}
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
